<template>
  <div>
    <div v-if="false">
      如果以下3,2,1的步骤均可单独使用，则可以测试这个全自动执行
      <button type="button" @click="allAutoInit()">测试全自动执行</button>
      <hr>
      <p>当前页面地址是：<pre>{{ windowLocationHref }}</pre></p>
      <p>记得打开F12查看请求</p>

      <hr>
      <dl>
        <dt>第一步：尝试获取unionid:<code>{{unionid || '__'}}</code></dt>
        <dd><button type="button" @click="手动清空缓存()">手动清空缓存</button></dd>
        <dd>如果获取到unionid，意味着完全获取授权，点击
          <button type="button" @click="跳转到实际登录页面()">跳转到实际登录页面</button>
          跳转页面即可
        </dd>
        <dd>如果没有，则等待下面的步骤</dd>
      </dl>

      <hr>

      <dl>
        <dt>第二步：尝试获取wxCode：<code>{{wxCode || '__'}}</code></dt>
        <dd><pre>{{` { appId:${APPID},code:${wxCode} } `}}</pre></dd>
        <dd>来自回调后的地址栏，如果存在，意味着访问过<b>授权请求地址</b></dd>
        <dd>如果存在，则点击
          <button type="button" @click="发起wxcode获取unionid的请求()">发起wxcode获取unionid的请求</button>
        向服务端代理请求</dd>
        <dd>请求结果<pre>{{ res }}</pre></dd>
        <dd>如上述请求成功，请重洗检查第一步</dd>
      </dl>

      <hr>

      <dl>
        <dt>第三步：假设是首次访问，没有任何unionid或wxCode</dt>
        <dd>回调地址redirect_uri：<code>{{redirect_uri || '__'}}</code></dd>
        <dd>APPID:<code>{{APPID || '__'}}</code></dd>
        <!-- <dd>SECRET:<code>{{SECRET || '__'}}</code></dd> -->
        <dd><b>授权请求地址</b>：<pre>{{wxAuthUrl_1st || '__'}}</pre></dd>
        <dd>向授权请求地址请求授权
          <button type="button" @click="尝试获取授权()">尝试获取授权</button>
        </dd>
        <dd>该请求实际是重定向，</dd>
      </dl>
      <hr>
    </div>
  </div>
</template>
<script>
import storage from '@/assets/storage.js';
import { bus } from '@/main.js';
import { mapState, mapMutations } from 'vuex';
import Cookies from 'js-cookie';
export default {
  name: 'index',
  mixins: [], //混入
  components: {}, //组件
  props: {}, //集成属性
  data() {
    return {
      isDev: process.env.NODE_ENV == 'development',
      APPID: 'wx97936174b0807629', //公众号的唯一标识
      // SECRET: 'c9a158864220f40d9e70b270b1850ba8', //公众号的appsecret
      wxCode: null,
      unionid: null,

      urlArgs: null,
      redirect_uri: null,
      res: null,
    };
  },
  computed: {
    ...mapState([]),
    windowLocationHref:function(){
      return window.location.href
    },
    wxAuthUrl_1st: function() {
      const url = 'https://open.weixin.qq.com/connect/oauth2/authorize';
      let redirect_uri = window.location.origin + window.location.pathname;
      let params = {
        appid: this.APPID, //公众号的唯一标识，一般是项目依存的appid
        redirect_uri: redirect_uri, //授权后重定向的回调链接地址，一般指向现在的地址
        // redirect_uri:
        // 'https://ewhtml8no.chenxi18.com/Webs.Html/NoAccountVideoLiveRoom1/#/?roomId=2&unnId=oFhPh0tjyO1N5qg3M7_3N-ZsYAAU',
        response_type: 'code', //返回类型，请填写code（估计是固定配置）
        scope: 'snsapi_userinfo',
        state: 'state#wechat_redirect',
      };
      const queryString = this.$qs.stringify(params);
      return `${url}?${queryString}`;
    }, //第一步：用户同意授权，获取code

    wxAuthUrl_2nd: function() {
      const url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
      let params = {
        appid: this.APPID, //公众号的唯一标识，一般是项目依存的appid
        // secret: this.SECRET,
        code: this.wxCode,
        grant_type: 'authorization_code',
      };
      const queryString = this.$qs.stringify(params);
      return `${url}?${queryString}`;
    }, //第二步：通过code换取网页授权access_token
  },
  methods: {
    ...mapMutations([]),
    test: function() {
      console.log('test');
    },
    get缓存unionid:function(){
      let temp1 = this._.get(storage.getUrlArgs(), 'unionid', false);
      let temp2 = storage.getLS('unionid');
      let temp3 = Cookies.get('unionid');
      return temp1 || temp2 || temp3;
    },
    缓存unionid:function(unionid){
      if(unionid){
        Cookies.set('unionid', unionid, {});
        storage.setLS('unionid', unionid);
      }else{
        Cookies.remove('unionid')
        storage.removeLS('unionid')
      }
    },
    get缓存wxCode:function(){
      let temp1 = this._.get(storage.getUrlArgs(), 'code', false);
      let temp2 = storage.getLS('wxCode');
      let temp3 = Cookies.get('wxCode');
      return temp1 || temp2 || temp3;
    },
    缓存wxCode:function(wxCode){
      if(wxCode){
        Cookies.set('wxCode', wxCode, {});
        storage.setLS('wxCode', wxCode);
      }else{
        Cookies.remove('wxCode')
        storage.removeLS('wxCode')
      }
    },

    尝试获取授权: function() {
      // 一般是初次请求，没有wxCode，所以向wx请求授权
      this.缓存wxCode()
      window.location.href = this.wxAuthUrl_1st;
    },

    parseQueryParams: function() {
      // 获取当前 URL
      const currentUrl = window.location.href;
      // 提取 query 部分（假设 URL 格式为 http://example.com?foo=bar&baz=qux）
      const queryString = currentUrl.split('?')[1] || '';
      // 使用 qs 解析 query 参数
      return this.$qs.parse(queryString);
    },
    手动清空缓存:function(){
      window.localStorage.removeItem('unionid')
    },
    跳转到实际登录页面: function(unionid) {
      // 必要的参数检查和获取
      if(!this.unionid&&this.unionid=='undefined'){
        return
      }
      let temp = storage.getLS('tempUrlArgs'); //一般在回跳后需要从本地缓存中取回参数

      let trq = storage.getUrlArgs();
      
      let q =  Object.assign({},trq,temp,{
        unionid: this.unionid,
      })
      let objUrl = storage.addQueryParamsToUrl(this.redirect_uri+'#'+'/client',q)
      window.location.href = objUrl
      // this.$router.push({
      //   path: '/client',
      //   query:q
      // });

    },
    
    发起wxcode获取unionid的请求: function() {
      let url = 'https://wxfwyun.chenxi18.com/Promote/GetunionidBySubions';
      let params = {
        appId: this.APPID,
        code: this.wxCode,
      };
      // this.$toasted.show('appId:' + params.appId);
      // this.$toasted.show('code:' + params.code);
      return this.$axios
        .get(url, { params: params })
        .then((res) => {
          this.res = res;
          if (res.statusCode == 200 && res.result) {
            let unionId = this._.get(res,'result.unionId');
            return Promise.resolve( unionId );
          }
        }).then(unionId=>{
          this.缓存unionid(unionId)
          this.$set(this,'unionid',unionId);
          return Promise.resolve(200)
        }).then( res => {
          // this.handleRendered();
        })
        .catch((err) => {
          // alert('err');
          console.error(err);
          let strerr = JSON.stringify(err);
          this.res = strerr;
          // alert(strerr);
        })
        .finally((_) => {});
    },

    allAutoInit:function(){
      let isAnonymous = this._.get(this.$route.meta, 'anonymous'); //匿名
      // this.$toasted.show('isAnonymous:' + isAnonymous);
      this.wxCode = this.get缓存wxCode();
      this.unionid = this.get缓存unionid();
      // this.$toasted.show('wxCode_1:' + this.wxCode);
      // this.$toasted.show('unionid_1:' + this.unionid);
      // wxCode
      // 061MHV0007HSsT1Ygp100Tvk5T1MHV0x
      // unionid
      // oFhPh0sO1G26n4v_8X4G7sl4nHAU
      if (isAnonymous) {
        //匿名:true
        this.handleRendered();
      } else {
        if (!this.wxCode) {
          this.$toasted.show('未授权登录，请求微信授权');
          // this.$toasted.show('wxCode_2:' + this.wxCode);
          // this.$toasted.show('unionid_2:' + this.unionid);
          try {
            // 一般是初次请求，没有wxCode，所以向wx请求授权
            // if(this.isDev){debugger }
            this.尝试获取授权();
          } catch (error) {
            // this.$toasted.show(JSON.stringify(error));
          }
        }else{
          this.缓存wxCode(this.wxCode)
        }
        if (!this.unionid) {
          // this.$toasted.show('wxCode_3:' + this.wxCode);
          // this.$toasted.show('unionid_3:' + this.unionid);
          try {
            this.发起wxcode获取unionid的请求().then((res)=>{
              this.handleRendered();
            });
          } catch (error) {
            
            // this.$toasted.show(JSON.stringify(error));
          }
        }else{
          this.缓存unionid(this.unionid)
        }
        if(this.wxCode&&this.unionid){
          this.handleRendered();
        }
        
        //匿名:false
      }
    }
  },
  beforeCreate: function() {},
  created: function() {},
  beforeMount: function() {},
  mounted: function() {
    this.redirect_uri = window.location.origin + window.location.pathname;
    let urlArgs = storage.getUrlArgs();
    if (this._.has(urlArgs, 'roomId')) {
      storage.setLS('tempUrlArgs', urlArgs);
    } // 一般首次访问时会带相关参数，将参数本地缓存，预防授权回调后的数据丢失

    new Promise((res,rej)=>{
      setTimeout(_=>{
        return res(200)
      },1000)
    }).then( res => {
      this.allAutoInit()
    }).catch( err => { console.error(err) }).finally( _ => {});
    
  },
  beforeUpdate: function() {},
  updated: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
};
</script>
<style lang="less" scoped></style>
